package com.graduationproject.examonline.verifyCode.controller;

import com.graduationproject.examonline.utils.Result;
import com.graduationproject.examonline.utils.VerifyCodeUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("api/verifyCode")
public  class VerifyCodeController {

    private Map<HttpSession, Map<String, Object>> verifyCodeMap = new HashMap<HttpSession, Map<String, Object>>();

    @GetMapping("getImage")
    public void getImage(HttpServletRequest req, HttpServletResponse res, HttpSession session){
        try{
            OutputStream outputStream=res.getOutputStream();
            res.setStatus(200);
            int w = 200, h = 80;
            String code = VerifyCodeUtils.generateVerifyCode(4);
            Map<String, Object> info = new HashMap<String, Object>();
            info.put("code", code);
            info.put("overTime", (new Date().getTime() + 1000*60*5));
            this.verifyCodeMap.put(session, info);
            VerifyCodeUtils.outputImage(w, h, outputStream, code);
            outputStream.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @GetMapping("checkVerifyCode")
    public Result checkVerifyCode(String code, HttpSession session) {
        try {
            Map<String, Object> trueInfo = verifyCodeMap.get(session);
            if (trueInfo != null) {
                long overTime = (long) trueInfo.get("overTime");
                String trueCode = (String) trueInfo.get("code");
                if (overTime > new Date().getTime()) {
                    if (trueCode.equals(code)) {
                        verifyCodeMap.remove(session);
                        return new Result(0, 200, "验证码正确");
                    }
                    return new Result(1, 200, "验证码错误");
                }
                verifyCodeMap.remove(session);
                return new Result(1, 200, "验证码已过期");
            }
            return new Result(1, 200, "验证码错误");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(2, 501, "服务器出错");
        }
    }
}

